package result

import (
	"fmt"
	"net/http"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
	"google.golang.org/grpc/status"

	"gitee.com/JianQiAIBackend/compkg/xerr"
)

func HttpResult(r *http.Request, w http.ResponseWriter, resp interface{}, err error) {
	if err == nil {
		// 成功返回
		if resp == nil {
			httpx.WriteJson(w, http.StatusOK, SuccessWithOutData())
		} else {
			httpx.WriteJson(w, http.StatusOK, Success(resp))
		}
	} else {
		// 错误返回
		errCode := xerr.ServerCommonErrCode
		errMsg := xerr.ErrMsgMap(xerr.ServerCommonErrCode)

		causeErr := errors.Cause(err)
		var e *xerr.CodeError
		if ok := errors.As(causeErr, &e); ok {
			// 自定义错误
			errCode = e.GetErrCode()
			errMsg = e.GetErrMsg()
		} else {
			// grpc错误
			if s, ok := status.FromError(causeErr); ok {
				errCode = uint32(s.Code())
				errMsg = s.Message()
			}
		}

		logx.WithContext(r.Context()).Errorf("【API-ERR】: %+v", err)

		httpx.WriteJson(w, http.StatusOK, Error(errCode, errMsg))
	}
}

func ParamErrorResult(r *http.Request, w http.ResponseWriter, err error) {
	logx.WithContext(r.Context()).Errorf("【API-ERR】: %+v", err)
	errMsg := fmt.Sprintf("%s ,%s", xerr.ErrMsgMap(xerr.RequestParamErrCode), err.Error())
	httpx.WriteJson(w, http.StatusBadRequest, Error(xerr.RequestParamErrCode, errMsg))
}

// MidValidErrorResult 中间件错误
func MidValidErrorResult(r *http.Request, w http.ResponseWriter, err error) {
	logx.WithContext(r.Context()).Errorf("【Mid-ERR】: %+v", err)
	errCode := xerr.ServerCommonErrCode
	errMsg := xerr.ErrMsgMap(xerr.ServerCommonErrCode)

	causeErr := errors.Cause(err)
	var e *xerr.CodeError
	if ok := errors.As(causeErr, &e); ok {
		// 自定义错误
		errCode = e.GetErrCode()
		errMsg = e.GetErrMsg()
	} else {
		// grpc错误
		if s, ok := status.FromError(causeErr); ok {
			errCode = uint32(s.Code())
			errMsg = s.Message()
		}
	}

	httpx.WriteJson(w, http.StatusOK, Error(errCode, errMsg))
}
